<template>
	<!-- 表单部分 -->
	<view class="form-box shadow">
		<view class="form-group">
			<view class="title must">标题</view>
		</view>
		<view class="form-group">
			<input placeholder="简短的标题" placeholder-class="phc" v-model="formTitle" maxlength="50"></input>
		</view>
		<!-- <view v-if="formTitleFocus" class="hint-desc error">标题不能为空</view> -->
		<div class="input-group">
			<label class="password-label">分类</label>
			<div class="kaoyb">
				<picker @change="bindPickerChange1" :value="isarray1" :range="array1">
					<view class="uni-input">{{ array1[isarray1] }} <text class="kuoyi">></text></view>
				</picker>
			</div>
		</div>

		<view class="form-group">
			<view class="title must">排序号<text class="text-grey text-normal margin-left-xs">(小的先显示)</text></view>
			<input placeholder="排序号，小的先显示" type="number" placeholder-class="phc" v-model="formOrder"
				maxlength="4"></input>
		</view>
		<!-- <view v-if="formOrderFocus" class="hint-desc error">排序号不能为空</view> -->

		<view class="form-group" style="display: flex; ">
			<view class="action text-bold text-l">简介</view>
			<view class="action" style="margin-left: 11px;">{{formDesc.length}}/100</view>
		</view>
		<view class="form-group align-start">
			<textarea placeholder-class="phc" placeholder="请输入本文简介，若不填写则直接取内容前100个字作为简介" style="min-height:150rpx"
				v-model="formDesc" maxlength="100" auto-height></textarea>
		</view>
		<!-- <view v-if="formDescFocus" class="hint-desc error">简介不能为空</view> -->

		<view class="form-group arrow" style="display: flex; ">
			<view class="title must">详细内容<text class="text-grey text-normal margin-left-xs">(必填)</text></view>
			<view class="form-text" @click="goToContentAdmin">{{contentDesc}}</view>
		</view>
		<!-- <view v-if="formContentFocus" class="hint-desc error">详细内容不能为空</view> -->
		<!-- 下划线 -->
		<view class="underline"></view>
		<!-- 图片上传部分 -->
		<uni-section title="封面上传" type="line">
			<view class="example-body">
				<uni-file-picker v-model="imageValue" file-mediatype="image" mode="grid" :limit="1" @progress="progress"
					@select="select" />
			</view>
		</uni-section>
		<!-- 提交按钮 -->
		<button @click="bindFormSubmit" class="btn-admin margin-top-xs">提交</button>
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog cancelText="取消" confirmText="确定" title="温馨提示" :content="nrtsk"
				@confirm="dialogConfirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		showstatebyid,
		updDynamic,
		url
	} from '@/request/api.js';

	const formTitle = ref(''); //标题
	// const formTitleFocus = ref(false);
	const formOrder = ref(''); //排序号
	// const formOrderFocus = ref(false);
	const formDesc = ref(''); //简介
	// const formDescFocus = ref(false);
	const contentDesc = ref('未填写');
	// const formContentFocus = ref(false);
	const imageValue = ref([]);

	const nrtsk = ref('');
	const alertDialog = ref(null);
	const array1 = ref(['最新动态', '服务介绍']);
	const isarray1 = ref(0); //isarray1
	let isnull = '';
	let myfield;
	let minute;
	let id;
	let tempFilePaths;
	let myfields;
	let urlpath;
	onLoad(async (e) => {
		console.log("e", e.id);
		id = e.id;
		try {
			const req = await showstatebyid({
				id: e.id
			});
			const data = req.data.data;
			console.log(data);
			formTitle.value = data[0].title;
			formOrder.value = data[0].sequence;
			isarray1.value = data[0].classify === '最新动态' ? 0 : 1;
			formDesc.value = data[0].introduce;
			minute = data[0].minute;
			myfield = data[0].minute;
			let combinedJsonString = '[' + data[0].minute.replace(/}{/g, '},{') +
				']'; // 将多个 JSON 字符串合并为一个有效的 JSON 数组字符串
			let retrievedArray = JSON.parse(combinedJsonString); // 解析合并后的 JSON 数组字符串
			let typeCounts = {
				text: 0,
				image: 0
			};
			if (Array.isArray(retrievedArray)) {
				retrievedArray.forEach(item => {
					if (item.type === 'text') {
						typeCounts.text++;
						isnull += item.value.replace(/\s+/g, '');
					} else if (item.type === 'image') {
						typeCounts.image++;
					}
				});
			}
			contentDesc.value = `${typeCounts.text}段文字，${typeCounts.image}张图片`;;
			imageValue.value = [{
				'name': "file.txt",
				'extname': "txt",
				'url': url() + data[0].cover,
			}]
			urlpath = data[0].cover
		} catch (error) {
			console.error("请求失败:", error);
		}
	});
	//搜索跳转获取
	onShow(async () => {
		// 从本地存储中获取名为'typeCounts'的数据
		const typeCounts = uni.getStorageSync('typeCounts');
		console.log(typeCounts)
		if (typeCounts != '') {
			console.log('输入b为空');
			// if (formDesc.value.replace(/\s+/g, '') === '') {
			// 	formDesc.value = typeCounts.isnull;
			// }
			isnull = typeCounts.isnull;
			myfields = typeCounts.myField;
			contentDesc.value = `${typeCounts.text}段文字，${typeCounts.image}张图片`;

		} else {
			console.log('输入为空');
		}
		// 不管result是否为空，都从本地存储中删除'typeCounts'数据
		uni.removeStorageSync('typeCounts');
	});



	const bindPickerChange1 = (e) => { //获取分类的值
		console.log('picker1发送选择改变，携带值为', e.detail.value);
		isarray1.value = e.detail.value;
	};

	const select = (e) => {
		console.log('选择文件：', e);
		// imageValue.value = e.tempFilePaths[0];这个是网络地址要连接后端
		imageValue.value = e.tempFiles[0]; //这个是本地地址用于测试
		console.log('imageValue:', imageValue.value);
		tempFilePaths = e.tempFilePaths[0]
	};

	function goToContentAdmin() {
		console.log(minute)
		uni.navigateTo({
			url: `/pages/admin/Dynamic/edit/admin_Dynamic_edit?data=` + minute
		});
	}
	const dialogConfirm = () => {
		// console.log('点击确认');
	};
	// 上传图片方法
	const uploadImages = (file) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: url() + 'state/upload', // 服务器上传接口地址
				filePath: file, // 媒体文件路径
				name: 'file', // 必须填写的文件对应的 key，用于服务器端接收文件
				formData: {
					'user': 'test' // 需要额外上传的参数
				},
				success: function(uploadRes) {
					let response = uploadRes.data;
					try {
						let resData = JSON.parse(response);
						resolve(resData); // 使用 Promise 解决（resolve）成功的结果
					} catch (e) {
						reject(e); // 如果解析失败，使用 Promise 拒绝（reject）错误
					}
				},
				fail: function(uploadErr) {
					reject(uploadErr); // 上传失败，使用 Promise 拒绝（reject）错误
				}
			});
		});
	};


	function bindFormSubmit() {
		// 提交表单
		const validations = [{
				condition: formTitle.value.trim() === '',
				message: "[标题] 不能为空"
			},
			{
				condition: formOrder.value.trim() === '',
				message: "[排序号] 不能为空"
			},
			{
				condition: contentDesc.value.trim() === '未填写',
				message: "[详细内容] 不能为空"
			},
			{
				condition: formDesc.value.trim() === '' && isnull === '',
				message: "[简介] 不能为空"
			},
			{
				condition: imageValue.value === '',
				message: "请上传封面图"
			}
		];

		for (const {
				condition,
				message
			}
			of validations) {
			if (condition) {
				nrtsk.value = message;
				alertDialog.value.open();
				return;
			}
		}

		// 如果简介为空，设置为默认值
		if (formDesc.value.trim() === '') {
			formDesc.value = isnull;
		}
		//不修改封面和详情页面
		if (tempFilePaths == null && myfields == null) {
			// 上传封面图
			let istype = isarray1.value === 0 ? '最新动态' : '服务介绍';
			const data = {
				id: id,
				title: formTitle.value.trim(),
				classify: istype,
				sequence: formOrder.value.trim(),
				introduce: formDesc.value.trim(),
				minute: myfield, // 将更新后的数组转换为字符串
				cover: urlpath
			};
			console.log(data)
			return updDynamic(data).then((res) => {
				console.log(res)
				if (res.data.code === 200) {
					console.log('修改成功');
					uni.navigateTo({
						url: '/pages/admin/Dynamic/Dynamic'
					});
				} else {
					console.log(res.data.msg);
				}
			});

		} else if (tempFilePaths != null && myfields != null) {
			//修改封面和详情
			// 上传封面图
			uploadImages(tempFilePaths)
				.then(resData => {
					if (resData) {
						let combinedJsonString = '[' + myfields.replace(/}{/g, '},{') + ']';
						let retrievedArray = JSON.parse(combinedJsonString);

						// 使用 Promise.all 处理所有图片上传
						let uploadPromises = retrievedArray.map((item) => {
							if (item.type === 'image') {
								if (item.src.includes('state/images/')) {
									item.src = item.src
								}else{
								return uploadImages(item.src).then(resData => {
									item.src = resData.data.targetPath; // 更新 src 为新的图片地址
								});	
								}
							}
							return Promise.resolve(); // 如果不是图片，直接解析
						});

						// 等待所有图片上传完成
						return Promise.all(uploadPromises).then(() => {
							let istype = isarray1.value === 0 ? '最新动态' : '服务介绍';
							const data = {
								id: id,
								title: formTitle.value.trim(),
								classify: istype,
								sequence: formOrder.value.trim(),
								introduce: formDesc.value.trim(),
								minute: JSON.stringify(retrievedArray).replace(/\[|\]/g,
								''), // 将更新后的数组转换为字符串
								cover: resData.data.targetPath
							};
							console.log(data)
							return updDynamic(data).then((res) => {
								console.log(res)
								if (res.data.code === 200) {
									console.log('修改成功');
									uni.navigateTo({
										url: '/pages/admin/Dynamic/Dynamic'
									});
								} else {
									console.log(res.data.msg);
								}
							});
						});
					}
				})
				.catch(error => {
					console.error('上传失败:', error);
				});
		} else if (tempFilePaths != null && myfields == null) {
			//修改封面
			uploadImages(tempFilePaths)
				.then(resData => {
					if (resData) {
						// 等待所有图片上传完成
						let istype = isarray1.value === 0 ? '最新动态' : '服务介绍';
						const data = {
							id: id,
							title: formTitle.value.trim(),
							classify: istype,
							sequence: formOrder.value.trim(),
							introduce: formDesc.value.trim(),
							minute: myfield, // 将更新后的数组转换为字符串
							cover: resData.data.targetPath
						};
						console.log(data)
						return updDynamic(data).then((res) => {
							console.log(res)
							if (res.data.code === 200) {
								console.log('修改成功');
								uni.navigateTo({
									url: '/pages/admin/Dynamic/Dynamic'
								});
							} else {
								console.log(res.data.msg);
							}
						});
					}
				})
				.catch(error => {
					console.error('上传失败:', error);
				});
		} else if (tempFilePaths == null && myfields != null) {
			//只修改详情
			let combinedJsonString = '[' + myfields.replace(/}{/g, '},{') + ']';
			let retrievedArray = JSON.parse(combinedJsonString);

			// 使用 Promise.all 处理所有图片上传
			let uploadPromises = retrievedArray.map((item) => {
				if (item.type === 'image') {
					if (item.src.includes('state/images/')) {
						item.src = item.src
					} else {
						return uploadImages(item.src).then(resData => {
							item.src = resData.data.targetPath; // 更新 src 为新的图片地址
						});
					}
				}
				return Promise.resolve(); // 如果不是图片，直接解析
			});

			// 等待所有图片上传完成
			return Promise.all(uploadPromises).then(() => {
				let istype = isarray1.value === 0 ? '最新动态' : '服务介绍';
				const data = {
					id: id,
					title: formTitle.value.trim(),
					classify: istype,
					sequence: formOrder.value.trim(),
					introduce: formDesc.value.trim(),
					minute: JSON.stringify(retrievedArray).replace(/\[|\]/g, ''), // 将更新后的数组转换为字符串
					cover: urlpath
				};
				console.log(data)
				return updDynamic(data).then((res) => {
					console.log(res)
					if (res.data.code === 200) {
						console.log('修改成功');
						uni.navigateTo({
							url: '/pages/admin/Dynamic/Dynamic'
						});
					} else {
						console.log(res.data.msg);
					}
				});
			});
		}
	}
	// function bindFormSubmit() {
	// 	// 提交表单
	// 	if (formTitle.value.replace(/\s+/g, '') === '') {
	// 		nrtsk.value = "[标题] 不能为空";
	// 		alertDialog.value.open();
	// 		return;
	// 	}
	// 	if (formOrder.value.replace(/\s+/g, '') === '') {
	// 		nrtsk.value = "[排序号] 不能为空";
	// 		alertDialog.value.open();
	// 		return;
	// 	}
	// 	if (contentDesc.value.replace(/\s+/g, '') === '未填写') {
	// 		nrtsk.value = "[详细内容] 不能为空";
	// 		alertDialog.value.open();
	// 		return;
	// 	}
	// 	if (formDesc.value.replace(/\s+/g, '') === '' && isnull === '') {
	// 		nrtsk.value = "[简介] 不能为空";
	// 		alertDialog.value.open();
	// 		return;
	// 	} else {
	// 		if (formDesc.value.replace(/\s+/g, '') === '') {
	// 			formDesc.value = isnull
	// 		}
	// 	}
	// 	if (imageValue.value === '') {
	// 		nrtsk.value = "请上传封面图";
	// 		alertDialog.value.open();
	// 		return;
	// 	}

	// 	let istype = isarray1.value === 0 ? '最新动态' : '服务介绍';
	// 	const data = {
	// 		id: id,
	// 		title: formTitle.value.replace(/\s+/g, ''),
	// 		classify: istype,
	// 		sequence: formOrder.value.replace(/\s+/g, ''),
	// 		introduce: formDesc.value.replace(/\s+/g, ''),
	// 		minute: myfield,
	// 		cover: '/static/logo.png'
	// 		//imageValue.value
	// 	}
	// 	// console.log(formTitle.value.replace(/\s+/g, ''))
	// 	// console.log(istype);
	// 	// console.log(formOrder.value.replace(/\s+/g, ''));
	// 	// console.log(formDesc.value.replace(/\s+/g, ''));
	// 	// console.log(imageValue.value);
	// 	// console.log(myfield);
	// 	console.log(data);
	// 	updDynamic(data).then((res) => {
	// 		console.log(res);
	// 		if (res.data.code === 200) {
	// 			console.log('修改成功');
	// 			uni.navigateTo({
	// 				url: `/pages/admin/Dynamic/Dynamic`
	// 			});
	// 		} else {
	// 			console.log(res.data.msg);
	// 		}
	// 	});
	// }
</script>

<style scoped>
	.input-group {
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid #ebebeb;
		padding: 5px 0;
		margin-bottom: 10px;
	}

	.password-label {
		font-weight: bold;
		font-size: 18px;
	}

	.password-label::before {
		content: '*';
		color: red;
		margin-right: 6px;
		vertical-align: middle;
	}

	/* 页面背景 */
	page {
		background-color: #f9f9f9;
	}

	/* 表单盒子 */
	.form-box {
		background-color: #fff;
		border-radius: 10px;
		padding: 20px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		margin-bottom: 20px;
	}

	/* 表单组 */
	.form-group {
		margin-bottom: 10px;
	}

	/* 标题 */
	.title {
		font-size: 18px;
		color: #333;
		font-weight: bold;
	}

	.must::before {
		content: '*';
		color: red;
		margin-right: 5px;
	}

	/* 输入框和文本域 */
	input,
	textarea {
		width: 93%;
		padding: 10px;
		border: 1px solid #ebebeb;
		border-radius: 4px;
		font-size: 16px;
		color: #333;
	}

	textarea {
		min-height: 150px;
	}

	/* 选择器箭头 */
	.arrow::after {
		content: '>';
		font-size: 16px;
		color: #888;
		margin-left: 5px;
	}

	/* 提示信息 */
	.hint-desc {
		font-size: 14px;
		color: #888;
	}

	.error {
		color: red;
	}

	/* 操作文本 */
	.action {
		font-size: 16px;
		color: #333;
	}

	/* 表单文本 */
	.form-text {
		font-size: 16px;
		color: #f56c6c;
		margin-left: 130px;
	}

	/* 提交按钮 */
	.btn-admin {
		display: block;
		width: 100%;
		padding: 12px;
		border-radius: 5px;
		background-color: #409eff;
		color: #fff;
		font-size: 18px;
		border: none;
		outline: none;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.btn-admin:hover {
		background-color: #66b1ff;
	}

	/* 图片上传 */
	/* (cmpt-img-upload) {
  根据实际组件样式进行调整
} */

	/* 间距 */
	.margin-top-xs {
		margin-top: 10px;
	}

	/* 文本颜色 */
	.text-grey {
		color: #888;
	}

	.text-normal {
		font-weight: normal;
	}

	.text-orange {
		color: #f56c6c;
	}

	.underline {
		height: 2px;
		background-color: #ebebeb;
		width: 100%;
		margin-top: 20px;
	}
</style>